<?php

namespace common\models\shop;

use Yii;
use common\models\keyword\KeywordRelation;
use common\helpers\Url;
use common\helpers\ArrayHelper;
use common\models\member\Member;
use common\logics\ShareLogic;
use yii\imagine\Image;
use common\helpers\FileHelper;

/**
 * This is the model class for table "{{%shop_product}}".
 *
 * @property int $id
 * @property string $name 产品名称
 * @property string $art_no 货号
 * @property string $slogan 促销语
 * @property string $description 简介描述
 * @property string $cover 货品缩略图
 * @property int $material 货物类型：0实物，1虚拟商品
 * @property int $min 起订量
 * @property string $store_id 店铺ID
 * @property string $type_id 分类ID
 * @property string $brand_id 品牌ID
 * @property string $template_id 快递模版ID
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property string $deleted_at 删除时间
 */
class ShopProduct extends \common\db\ActiveRecord implements \common\base\ShareDataInterface {

    /**
     * 商品状态
     * 默认0，上架1，删除-1
     */
    CONST STATUS_DEFAULT = 0;
    CONST STATUS_ACTIVE = 10;
    CONST STATUS_DELETED = -1;

    /**
     * 新品展示周期（天）
     */
    const NEW_PRODUCT_SHOW_PERIOD = 7;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%shop_product}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['name', 'art_no', 'slogan', 'cover'], 'required'],
            [['material', 'type_id', 'store_id', 'brand_id', 'min', 'template_id', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['name', 'slogan'], 'string', 'max' => 50],
            [['description'], 'string', 'max' => 100],
            [['art_no'], 'string', 'max' => 32],
            [['cover'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '产品名称',
            'art_no' => '货号',
            'slogan' => '促销语',
            'description' => '简介描述',
            'cover' => '货品缩略图',
            'material' => '货物类型：0实物，1虚拟商品',
            'store_id' => '店铺ID',
            'min' => '起订量',
            'type_id' => '分类ID',
            'brand_id' => '品牌ID',
            'template_id' => '快递模版ID',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    /**
     * 关联商品详情
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getData() {
        return $this->hasOne(ShopProductData::className(), ['product_id' => 'id']);
    }

    /**
     * 关联商品详情
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getType() {
        return $this->hasOne(ShopType::className(), ['id' => 'type_id']);
    }

    /**
     * 关联商品详情
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getTypeSpecs() {
        return $this->hasMany(ShopTypeSpec::className(), ['type_id' => 'id'])->via('type')->orderBy(['id' => SORT_DESC]);
    }

    /**
     * 关联商品缩略图列表
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getAlbum() {
        return $this->hasMany(ShopAttachment::className(), ['product_id' => 'id'])->orderBy([
            'listorder' => SORT_ASC
        ]);
    }

    /**
     * 关联商品栏目
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getCategories() {
        return $this->hasMany(ShopProductCategory::className(), ['product_id' => 'id']);
    }

    /**
     * 关联商品栏目信息
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getCategory() {
        return $this->hasMany(ShopCategory::className(), ['id' => 'category_id'])
        ->via('categories');
    }

    /**
     * 关联商品信息
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getGoods() {
        return $this->hasMany(ShopGoods::className(), ['product_id' => 'id'])->active();
    }

    /**
     * 关联商品信息
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getSkus() {
        return $this->hasMany(ShopGoods::className(), ['product_id' => 'id']);
    }

    /**
     * 关联商品规格
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getSpecs() {
        return $this->hasMany(\common\models\views\ViewSkuSpec::className(), ['product_id' => 'id']);
    }
    
    /**
     * 关联商品规格
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getActiveSpecs() {
        return $this->getSpecs()->active();
    }

    /**
     * 关联商品统计信息
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getStats() {
        return $this->hasOne(ShopProductStats::className(), ['product_id' => 'id']);
    }

    /**
     * 关联商品运费模版
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getTemplate() {
        return $this->hasOne(\common\models\freight\FreightTemplate::className(), ['id' => 'template_id']);
    }

    /**
     * 关联商品收藏数
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getCollects() {
        return $this->hasMany(ShopFavorite::className(), ['product_id' => 'id']);
    }

    /**
     * 是否已收藏商品
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getCollected() {
        return $this->hasOne(ShopFavorite::className(), ['product_id' => 'id'])->andWhere([
            'user_id' => Yii::$app->user->id
        ])->exists();
    }

    public function getSales() {
        $sales = $this->stats ? $this->stats->sales : 1;
        return intval($sales * pi());
    }

    /**
     * 商品检索关键字
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getKeywords() {
        return $this->hasMany(KeywordRelation::className(), ['model_id' => 'id'])->andWhere([
            'model' => KeywordRelation::MODEL_GOODS
        ]);
    }

    /**
     * 商品价格
     * @return string
     */
    public function getPrice() {
        $price = 0;
        $prices = ArrayHelper::getColumn($this->goods, function($item) {
            return $item->price - $item->discount;
        }, []);
        if (!empty($prices)) {
            $price = min($prices);
        }
        return number_format($price, 2, '.', '');
    }

    /**
     * 商品价格
     * @return string
     */
    public function getOriginalPrice() {
        $price = 0;
        $prices = ArrayHelper::getColumn($this->goods, 'price', []);
        if (!empty($prices)) {
            $price = min($prices);
        }
        return number_format($price, 2, '.', '');
    }

    /**
     * 商品会员价格
     * @return string
     */
    public function getMemberPrice() {
        $user = Yii::$app->user->identity;
        $discount = 1;
        if ($user) {
            $discount = $user->discount;
        }
        return number_format($this->price * $discount, 2, '.', '');
    }

    /**
     * 商品市场价格（原价）
     * @return string
     */
    public function getMarketPrice() {
        if ($this->price - $this->memberPrice > 0) {
            return $this->price * 1;
        }
        return 0;
    }

    /**
     * 是否新品
     * @return boolean
     */
    public function getNewest() {
        return $this->created_at + self::NEW_PRODUCT_SHOW_PERIOD * 86400 > time();
    }

    /**
     * 关联商品运费模版
     * @return \yii\db\ActiveQueryInterfac the relational query object.
     */
    public function getFreeShipping() {
        if ($this->template) {
            return boolval($this->template->free);
        }
        return true;
    }

    /**
     * 商品封面
     * @return string
     */
    public function getThumb() {
        return Url::attach($this->cover);
    }

    /**
     * 商品封面
     * @return string
     */
    public function getShareIcon() {
        $uploadPath = '/share' . $this->cover;
        $savepath = Yii::getAlias('@uploads' . $uploadPath);
        if (YII_ENV_PROD && !file_exists($savepath)) {
            FileHelper::createDirectory(dirname($savepath));
            Image::thumbnail('@uploads' . $this->cover, 120, 120)->save($savepath, ['quality' => 90]);
        }
        return Url::attach($uploadPath);
    }

    /**
     * 商品详情
     * @return string
     */
    public function getDetail() {
        $data = $this->data;
        if ($data) {
            return $data->body;
        }
        return '暂无商品详情';
    }

    /**
     * 商品H5页面地址
     * @return string
     */
    public function getWeblink() {
        return Url::weblink('goods/{id}', [
            'id' => $this->id
        ]);
    }

    /**
     * 商品APP原生页面地址
     * @return string
     */
    public function getNativelink() {
        return Url::weblink('shop.product', [
            'id' => $this->id
        ]);
    }

    /**
     * 获取商品分享数据
     * @return array
     */
    public function getShareData() {
        $model = new ShareLogic();
        $model->setAttributes([
            'type' => ShareLogic::TYPE_GOODS,
            'title' => $this->name,
            'content' => $this->description,
            'thumb' => $this->shareIcon,
        ]);
        $model->setParams([
            'id' => $this->id,
        ]);
        return $model->toArray();
    }

    /**
     * 通过分享ID查询文章
     * @return array
     */
    public static function findShareById($id) {
        $model = static::findOne($id);
        if (!$model) {
            return null;
        }
        return $model->shareData();
    }

}
